<?php

namespace App\Http\Controllers\Home;

use App\Models\Formula;
use App\Models\Project;
use App\Models\Settlement;
use Illuminate\Http\Request;
use App\Models\Budget;
use App\Models\BudgetRow;
use APP\Models\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class BudgetController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request ,$id)
    {
        $settlement = Settlement::where("id","=",$id)->first();
        $project_id = $settlement->project_id;
        $project = Project::where("id","=",$project_id)->first();
        $link = [
            "pname"=> $project->project_name,
            "cname"=> $settlement->name,
            "pid"=>$project_id,
            "cid"=>$id
        ];
        $Budgets    = Budget::where("project_id" ,"=" ,$id)->orderBy('budget_id', 'asc')->get();
        if( empty($Budgets) ){
            return redirect()->back()->withErrors("暂无数据");
        }
		
        $Sheets     = [];
        $Formulas   = [];
        $Sheet_Index= 1;
        $Sheet_Name = [];
        foreach($Budgets as $Budget) {
            $BudgetRows = BudgetRow::where("budget_id" ,"=" ,$Budget->budget_id)->orderBy('budget_row_id', 'asc')->get();
            if(count($BudgetRows) == 0){
                continue;
            }
            $config = json_decode($Budget->sheet_data ,true);
            //$config["id"] = $Budget->budget_id;
            //$config["rows"] = [];
            $_Sheet_Name = "sheet_" . $Sheet_Index;
            if(isset($config["sheet_name"])){
                $_Sheet_Name = $config["sheet_name"];
            }
            $Sheet_Name[] = $_Sheet_Name;
            $sheet_formulas = array();
            $sheet_formulas['id'] = $Budget->budget_id;
            $sheet_formulas['formulas'] = Formula::where("budget_id" ,"=" ,$Budget->budget_id)->get()->toArray();
            $Formulas[] = $sheet_formulas;
            /*
            $rows_count = 0;
            $sheet_formulas = array();
            $sheet_formulas['id'] = $Budget->budget_id;
            $sheet_formulas['formulas'] = Formula::where("budget_id" ,"=" ,$Budget->budget_id)->get()->toArray();
            $Formulas[] = $sheet_formulas;
            foreach ($BudgetRows as $BudgetRow){
                $rows = json_decode($BudgetRow->row_data ,true);
                array_unshift($rows ,$this->getValue($BudgetRow));
                unset( $BudgetRow->row_data );
                array_unshift($rows ,$BudgetRow);
                $count = count($rows);
                if($rows_count < $count){
                    $rows_count = $count;
                }
                $config["rows"][] = $rows;
            }
            $config["columns"]      = [];//隐藏第一列
            for($i = 1 ; $i < $rows_count ;$i++){
                $config["columns"][] = array("data"=> $i);
            }
            $Sheets[] = str_replace('"', '\\"', str_replace("'" ,"\\'",json_encode($config)));
            */
            $Sheet_Index++;
        }
        if( empty($settlement->excel) ){
            $settlement->excel = '#';
        }
        if( empty($settlement->drawing) ){
            $settlement->drawing = '#';
        }
        return view('home.budget.index' ,array("sheetnames"=>$Sheet_Name ,"formulas"=>$Formulas ,"links"=>$link, 'settlement'=>$settlement ,"id"=>$id));
    }
	
	public function getBudget($id ,$encode_json = true){
        $Budgets = [];
        $objects = Budget::where("project_id" ,"=" ,$id)->orderBy('budget_id', 'asc')->get();

        foreach($objects as $object) {
            $budget_rows_objects = BudgetRow::where("budget_id" ,"=" ,$object->budget_id)->orderBy('budget_row_id', 'asc')->get();
            if(count($budget_rows_objects) == 0){
                continue;
            }
            $config = json_decode($object->sheet_data ,true);
            $config["id"] = $object->budget_id;
            $config["rows"] = [];
            $rows_count = 0;
            foreach ($budget_rows_objects as $budget_rows){
                $rows = json_decode($budget_rows->row_data ,true);
                $str = array();
                if($budget_rows->row_confirm_1 == 1){
                    $str[] = "业主已确认";
                }else{
                    $str[] = "业主未确认";
                }
                if($budget_rows->row_confirm_2 == 1){
                    $str[] = "承包单位已确认";
                }else{
                    $str[] = "承包单位未确认";
                }
                if($budget_rows->row_confirm_3 == 1){
                    $str[] = "咨询单位已确认";
                }else{
                    $str[] = "咨询单位未确认";
                }
                array_unshift($rows ,"取消|" .join("-",$str));
                array_unshift($rows ,$budget_rows->budget_row_id);

                $count = count($rows);
                if($rows_count < $count){
                    $rows_count = $count;
                }
                $config["rows"][] = $rows;
            }
            $config["columns"] = [];//隐藏第一列
            for($i = 1 ; $i < $rows_count ;$i++){
                $config["columns"][] = array("data"=> $i);
            }
            if($encode_json){
                $Budgets[] = str_replace('"', '\\"', str_replace("'" ,"\\'",json_encode($config)));
            }else{
                $Budgets[] = $config;
            }
        }
        return $Budgets;
    }

    public function confirm($id){
        if(session("user")->user_role == "业主"){
            BudgetRow::where("budget_row_id" ,"=" ,$id)->update(array("row_confirm_1"=>1 ,"row_confirm_1_at"=>date("Y-m-d H:i:s")));
        }elseif(session("user")->user_role == "承包单位"){
            BudgetRow::where("budget_row_id" ,"=" ,$id)->update(array("row_confirm_2"=>1 ,"row_confirm_2_at"=>date("Y-m-d H:i:s")));
        }elseif(session("user")->user_role == "咨询单位"){
            BudgetRow::where("budget_row_id" ,"=" ,$id)->update(array("row_confirm_3"=>1 ,"row_confirm_3_at"=>date("Y-m-d H:i:s")));
        }
        $row = BudgetRow::where("budget_row_id" ,"=" ,$id)->first();
        unset( $row["row_data"] );
        return response()->json($row);
    }


    public function objections(Request $request){
        if($request->ajax()) {
            $objection = json_decode($request->getContent(), true);
            $budget_id = $objection['id'];
            foreach ($objection["data"] as $row){
                if($row["formula_id"] == 0){
                    $f = new Formula();
                    $f->budget_id = $budget_id;
                    $f->location  = $row["location"];
                    $f->old_value = $row["old_value"];
                    $f->new_value = $row["new_value"];
                    $f->user_id   = session('user')->id;
                    $f->reason = $row["reason"];
                    $f->remark = $row["remark"];
                    $f->save();
                }else{
                    Formula::where("formula_id" ,"=" ,$row["formula_id"])->update([
                        "location"=>$row["location"],
                        "old_value"=>$row["old_value"],
                        "new_value"=>$row["new_value"],
                        "reason"=>$row["reason"],
                        "remark"=>$row["remark"]
                    ]);
                }
            }
            return response()->json(array("success"=>true));
        }
        return response()->json(array("success"=>false));
    }


    protected function getValue($BudgetRow){
        if(session("user")->user_role == "业主"){
            if($BudgetRow->row_confirm_1 == 1){
                return "已确认";
            }
            return "确认";
        }elseif(session("user")->user_role == "承包单位"){
            if($BudgetRow->row_confirm_2 == 1){
                return "已确认";
            }
            return "确认";
        }elseif(session("user")->user_role == "咨询单位"){
            if($BudgetRow->row_confirm_2 == 1){
                return "已确认";
            }
            return "确认";
        }else{
            return '未知';
        }
    }


    public function getSheets(Request $request ,$id) {
        $Sheets     = [];
        $Budgets    = Budget::where("project_id" ,"=" ,$id)->orderBy('budget_id', 'asc')->get();
        foreach($Budgets as $Budget) {
            $BudgetRows = BudgetRow::where("budget_id" ,"=" ,$Budget->budget_id)->orderBy('budget_row_id', 'asc')->get();
            if(count($BudgetRows) == 0){
                continue;
            }
            $config = json_decode($Budget->sheet_data ,true);
            $config["id"] = $Budget->budget_id;
            $config["rows"] = [];

            $rows_count = 0;
            $sheet_formulas = array();
            $sheet_formulas['id'] = $Budget->budget_id;
            $sheet_formulas['formulas'] = Formula::where("budget_id" ,"=" ,$Budget->budget_id)->get();
            $Formulas[] = $sheet_formulas;
            foreach ($BudgetRows as $BudgetRow){
                $rows = json_decode($BudgetRow->row_data ,true);
                array_unshift($rows ,$this->getValue($BudgetRow));
                unset( $BudgetRow->row_data );
                array_unshift($rows ,$BudgetRow);
                $count = count($rows);
                if($rows_count < $count){
                    $rows_count = $count;
                }
                $config["rows"][] = $rows;
            }
            $config["columns"]      = [];//隐藏第一列
            for($i = 1 ; $i < $rows_count ;$i++){
                $config["columns"][] = array("data"=> $i);
            }
            $Sheets[] = $config;
        }
        return response()->json( $Sheets );
    }

    public function show(Request $request, $id){
        $settlement = Settlement::where("id","=",$id)->first();
        $project_id = $settlement->project_id;
        $project = Project::where("id","=",$project_id)->first();
        $link = [
            "pname"=> $project->project_name,
            "cname"=> $settlement->name,
            "pid"=>$project_id,
            "cid"=>$id
        ];
        $Budgets    = Budget::where("project_id" ,"=" ,$id)->orderBy('budget_id', 'asc')->get();
        if( empty($Budgets) ){
            return redirect()->back()->withErrors("暂无数据");
        }

        $Sheets     = [];
        $Formulas   = [];
        $Sheet_Index= 1;
        $Sheet_Name = [];
        foreach($Budgets as $Budget) {
            $BudgetRows = BudgetRow::where("budget_id" ,"=" ,$Budget->budget_id)->orderBy('budget_row_id', 'asc')->get();
            if(count($BudgetRows) == 0){
                continue;
            }
            $config = json_decode($Budget->sheet_data ,true);
            //$config["id"] = $Budget->budget_id;
            //$config["rows"] = [];
            $_Sheet_Name = "sheet_" . $Sheet_Index;
            if(isset($config["sheet_name"])){
                $_Sheet_Name = $config["sheet_name"];
            }
            $Sheet_Name[] = $_Sheet_Name;
            $sheet_formulas = array();
            $sheet_formulas['id'] = $Budget->budget_id;
            $sheet_formulas['formulas'] = Formula::where("budget_id" ,"=" ,$Budget->budget_id)->get()->toArray();
            $Formulas[] = $sheet_formulas;
            /*
            $rows_count = 0;
            $sheet_formulas = array();
            $sheet_formulas['id'] = $Budget->budget_id;
            $sheet_formulas['formulas'] = Formula::where("budget_id" ,"=" ,$Budget->budget_id)->get()->toArray();
            $Formulas[] = $sheet_formulas;
            foreach ($BudgetRows as $BudgetRow){
                $rows = json_decode($BudgetRow->row_data ,true);
                array_unshift($rows ,$this->getValue($BudgetRow));
                unset( $BudgetRow->row_data );
                array_unshift($rows ,$BudgetRow);
                $count = count($rows);
                if($rows_count < $count){
                    $rows_count = $count;
                }
                $config["rows"][] = $rows;
            }
            $config["columns"]      = [];//隐藏第一列
            for($i = 1 ; $i < $rows_count ;$i++){
                $config["columns"][] = array("data"=> $i);
            }
            $Sheets[] = str_replace('"', '\\"', str_replace("'" ,"\\'",json_encode($config)));
            */
            $Sheet_Index++;
        }
        if( empty($settlement->excel) ){
            $settlement->excel = '#';
        }
        if( empty($settlement->drawing) ){
            $settlement->drawing = '#';
        }
        return view('home.budget.show' ,array("sheetnames"=>$Sheet_Name ,"formulas"=>$Formulas ,"links"=>$link, 'settlement'=>$settlement ,"id"=>$id));
    }
}